//
//  SYPhotoBrowserViewController.swift
//  SingWeibo
//
//  Created by shiying on 15/12/31.
//  Copyright © 2015年 shiying. All rights reserved.
//

import UIKit
import SVProgressHUD

class SYPhotoBrowserViewController: UIViewController {

    let ReuseIdentifier = "ReuseIdentifier"
    private var selectedIndexPath: NSIndexPath
    private var models: [SYPhotoBrowserModel]
    
    let margin: CGFloat = 10 /// 间距
    
    private let layout = UICollectionViewFlowLayout() /// 流水布局
    
    init(indexPath: NSIndexPath, models: [SYPhotoBrowserModel]) {
        self.selectedIndexPath = indexPath
        self.models = models
        super.init(nibName: nil, bundle: nil)
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareUI()

    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        setupPage(selectedIndexPath.item + 1)
    }
    
    func setupPage(currentPage: Int) {
        pageLabel.text = "\(currentPage)/\(models.count)"
    
    }
    
    // 准备UI
    func prepareUI() {
        view.addSubview(collectionView)
        view.addSubview(pageLabel)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageLabel.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        
        /*view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))*/
        
        collectionView.frame = CGRect(x: 0, y: 0, width: (view.bounds.width + margin), height: view.bounds.height)
        
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 20))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[close(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["close" : closeButton]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[save(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["save" : saveButton]))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[close(75)]-(>=0)-[save(75)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["close" : closeButton, "save" : saveButton]))
    
        
        setupCollectionVeiw()
    }
    /// 设置 CollectionVeiw
    private func setupCollectionVeiw() {
        
        collectionView.registerClass(SYPhotoBrowserCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        // 设置大小
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        collectionView.pagingEnabled = true
        collectionView.bounces = false
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: margin)
    
    }
    
    // MARK: - 按钮的点击事件
    func close() {
    
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    // MARK: - 保存图片
    func save() {
    
        // 获取选中的indexPath
        let cell = collectionView.cellForItemAtIndexPath(selectedIndexPath) as! SYPhotoBrowserCell
        
        if let image = cell.imageView.image {
        
            //- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
            UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        } else {
            SVProgressHUD.showErrorWithStatus("没有图片")
        }
        
    }
    // 保存图片的回调 
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存图片出错")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存图片成功")
        }
    }
    
    // MARK: - 懒加载
    lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    
    lazy var pageLabel: UILabel = UILabel(fontSize: 13, color: UIColor.whiteColor())
    
    
    lazy var closeButton: UIButton = {
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
        button.setTitle("关闭", forState: UIControlState.Normal)
        button.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    lazy var saveButton: UIButton = {
        let button = UIButton()
    
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
        button.setTitle("保存", forState: UIControlState.Normal)
        button.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    /// 背景视图
    private lazy var backGroundView: UIView = {
        let view = UIView()
        
        view.backgroundColor = UIColor.blackColor()
        
        return view
    }()
}

extension SYPhotoBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! SYPhotoBrowserCell
//        cell.backgroundColor = UIColor.randomColor()
        let model = models[indexPath.item]
        cell.imageURL = model.largeURL
        cell.cellDelegate = self
        print("\(models[indexPath.item])")
        
        return cell
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        selectedIndexPath = NSIndexPath(forItem: index, inSection: 0)
        setupPage(index + 1)
    }
    
}

extension SYPhotoBrowserViewController: SYPhotoBrowserCellDelegate {
    func viewForTransparent() -> UIView {
        return backGroundView
    }

    func cellForDissmissController() {
        dismissViewControllerAnimated(false, completion: nil) // true有转场动画，false没有
    }
    
    func targetRectForDismissController() -> CGRect {
        return dismissTargetRect()
    }

}

extension SYPhotoBrowserViewController: UIViewControllerTransitioningDelegate {

    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SYPhotoBrowserModalAnimated()
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SYPhotoBrowserDismissAnimated()
    }
}

// MARK: - 转场动画相关的元素
extension SYPhotoBrowserViewController {

    /// 生成modal 时的过度视图
    func modalTempImageView() -> UIImageView {
        // 创建过度视图
        let tempImageView = UIImageView()
        
        // 获取到对应的模型
        let model = models[selectedIndexPath.item]
        
        // 获取缩略图的imageView
        let imageView = model.imageView!
        
        // 设置过度视图的image
        tempImageView.image = imageView.image
        
        // 设置缩放模式
        tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
        tempImageView.clipsToBounds = true // 切割
        
        // 坐标系转换
        let newFrame = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
        // 设置frame
        tempImageView.frame = newFrame
        return tempImageView
    }

    // 计算modal 的最终位置
    func modalTargetRect() -> CGRect {
        
        // 这个时候大图不一定有，我可以拿小图来计算，新浪小图和大图长宽比都是一样的
        let model = models[selectedIndexPath.item]
        
        // 获取缩略图，不能强制折包，如果没有图片，就不计算大小
        if let image = model.imageView?.image {
            let newWidth = UIScreen.mainScreen().bounds.width
        
            let newHeight = newWidth * image.size.height / image.size.width
        
            var offsetY: CGFloat = 0
            
            // 判断是长图还是短图
            if newHeight < UIScreen.mainScreen().bounds.height {
                // 短图
                offsetY = (UIScreen.mainScreen().bounds.height - newHeight) * 0.5
            } else {
            
            }
            return CGRect(x: 0, y: offsetY, width: newWidth, height: newHeight)
    }
        return CGRectZero

    }
    
    func dismissTempImageView() -> UIImageView {
        // 创建过渡视图
        let tempImageView = UIImageView()
        
        // 获取到正在显示的cell
        let cell = collectionView.cellForItemAtIndexPath(selectedIndexPath) as! SYPhotoBrowserCell
        // 获取到正在显示的image
        if let image = cell.imageView.image {
            // 设置过渡视图的image
            tempImageView.image = image
            
            // 设置过渡视图的frame 
            let newFrame = cell.imageView.superview!.convertRect(cell.imageView.frame, toCoordinateSpace: view)
        
            tempImageView.frame = newFrame
            
            // 设置填充模式
            tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
            tempImageView.clipsToBounds = true
        
        }
        // 返回
        return tempImageView
    }
    
    // 返回dismiss时的目标frame
    func dismissTargetRect() -> CGRect {
        // 获取到对应的模型
        let model = models[selectedIndexPath.item]
        
        // 获取缩略图
        let imageView = model.imageView!
        // 转换坐标系，从imageView的父控件转换到屏幕的左上角
        let newFrame = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
        return newFrame
    }
}
